<template>
  <div style="background-color: white; width: 100%; height: 100%">
    <el-button
      link
      @click="router.push('/ProducManagement/PurchasingsQuery')"
      style="margin-left: 10px"
      >‹返回</el-button
    >
    &nbsp;
    <span>|</span>
    &nbsp;
    <span style="font-size: 17px; font-weight: 500; color: green"
      > 采购/委外订单头信息 </span
    >


    
    <hr style="background-color: #d3d3d3; height: 1px; border: none" />

    
  <el-tabs type="border-card" style="margin-top: 30px;margin-left: 30px;">
    <el-tab-pane label="标准信息" >  
      <el-form  class="demo-ruleForm" :model="form" ref="formRef" label-width="auto" style="max-width: 1100px;margin-left: 180px;margin-top: 30px;">
            <el-form-item label="订单编码" style="margin: 40px;width: 500px;"  prop="purchasingNo" :rules="[ { required: true, message: '必填' },]">
                <el-input v-model="form.purchasingNo" :readonly="true" />
            </el-form-item>

            <el-form-item label="订单名称" style="width: 500px;float: right;margin-top: -72px;" prop="purchasingName" :rules="[ { required: true, message: '必填' },]">
                <el-input v-model="form.purchasingName" />
            </el-form-item>

            <el-form-item label="订单类型" style="margin: 40px;width: 500px;" prop="purchasingTypeId" :rules="[ { required: true, message: '必填' },]" >
            <el-select v-model="form.purchasingTypeId" placeholder="请选择">
              
            <el-option v-for="item in options" :label="item.purchasingTypeName" :value="item.purchasingTypeId"/>
            </el-select>
            </el-form-item>

            <el-form-item label="所属项目" style="width: 500px;float: right;margin-top: -72px;">
                <el-select v-model="form.projectId"  placeholder="请选择">
                    
                    <el-option v-for="item in options2" :label="item.projectName" :value="item.projectId"/>
            </el-select>
            </el-form-item>

            <el-form-item label="订单备注" style="margin: 40px;width: 1060px;" >
                <el-input v-model="form.purchasingDesc" type="textarea" />
            </el-form-item>


            <el-form-item label="供应商" style="margin: 40px;width: 500px;" prop="suppliersId" :rules="[ { required: true, message: '必填' },]">
                <el-select v-model="form.suppliersId" placeholder="请选择" >
                    
                    <el-option v-for="item in options1" :label="item.suppliersName" :value="item.suppliersId"/>
            </el-select>
            </el-form-item>

            <el-form-item label="订单金额（不含税）" style="width: 500px;float: right;margin-top: -72px;" >
                <el-input v-model="ruleForm.bankAmount" disabled/>
            </el-form-item>

            <el-form-item label="币种" style="margin: 40px;width: 500px;" prop="currency" :rules="[ { required: true, message: '必填' },]">
            <el-select v-model="form.currency" placeholder="请选择">
                <el-option label="人民币" value="人民币" />
                <el-option label="美元" value="美元" />
                <el-option label="欧元" value="欧元" />
                <el-option label="英镑" value="英镑" />
                <el-option label="日元" value="日元" />

            </el-select>
            </el-form-item>

            <el-form-item label="预收款金额" style="width: 500px;float: right;margin-top: -72px;" prop="advancePayment" :rules="[ { required: true, message: '必填' },]" >
                <el-input v-model="form.advancePayment" />
            </el-form-item>


            <el-form-item label="订单开始时间" style="margin: 40px;width: 500px;" >
                <el-col :span="11">
                    <el-date-picker
                    v-model="form.startTime"
                    type="date"
                    style="width: 365px"
                    />
                </el-col>
            </el-form-item>

            <el-form-item label="订单结束时间" style="width: 500px;float: right;margin-top: -72px;" >
                <el-col :span="11">
                    <el-date-picker
                    v-model="form.endTime"
                    type="date"
                    style="width: 365px"
                    />
                </el-col>
            </el-form-item>

            <el-form-item label="签订时间" style="margin: 40px;width: 500px;" prop="signUpTime" :rules="[ { required: true, message: '必填' },]">
                <el-col :span="11">
                    <el-date-picker
                    v-model="form.signUpTime"
                    type="date"
                    style="width: 365px"
                    />
                </el-col>
            </el-form-item>

            <el-form-item label="状态" style="width: 500px;float: right;margin-top: -72px;" prop="purchasingStatus" :rules="[ { required: true, message: '必填' },]">
                <el-select v-model="form.purchasingStatus"   >
                <el-option label="新建" :value="1" />
                <el-option label="确认" :value="2" />
            </el-select>
            </el-form-item>
            

            <el-form-item label="计税类型" style="margin: 40px;width: 500px;">
                <el-select v-model="form.taxType" >
                <el-option label="增值税" value="增值税" />
                <el-option label="附加税" value="附加税" />
            </el-select>
            </el-form-item>

            <el-form-item label="税率" style="width: 500px;float: right;margin-top: -72px;">
                <el-input v-model="form.taxRate" />
            </el-form-item>

            <el-form-item label="开票金额（含税）" style="margin: 40px;width: 500px;" disabled="true">
                <el-input v-model="form.billing" disabled/>
            </el-form-item>

            <el-form-item label="已收款金额（含税）" style="width: 500px;float: right;margin-top: -72px;">
                <el-input v-model="form.paidFor" disabled/>
            </el-form-item>

            <el-form-item label="制单人" style="margin: 40px;width: 500px;" prop="billMaking" :rules="[ { required: true, message: '必填' },]">
                <el-input v-model="form.billMaking" />
            </el-form-item>

            <el-form-item label="制单部门" style="width: 500px;float: right;margin-top: -72px;" prop="departmentId" :rules="[ { required: true, message: '必填' },]">
                <el-select v-model="form.departmentId" placeholder="请选择">
                    <el-option label="请选择" :value="0" />
                    <el-option v-for="item in options3" :label="item.departmentName" :value="item.departmentId"/>
            </el-select>
            </el-form-item>
            
            <el-button type="success" style="width: 83px;float: right;margin: 10px;" v-show="form.approvalStatus==0 || form.approvalStatus==3" @click="UpdatePurchasings">保存</el-button>
            <el-button type="primary" style="width: 83px;float: right;margin: 10px;" v-show="form.approvalStatus==0|| form.approvalStatus==3" @click="Submit1">提交</el-button>
            <el-button type="warning" style="width: 83px;float: right;margin: 10px;" v-show="form.approvalStatus==1" @click="Submit()">审核通过</el-button>
            <el-button type="danger" style="width: 83px;float: right;margin: 10px;" v-show="form.approvalStatus==1" @click="bohui()">驳回</el-button>
            <!-- <el-button type="danger" style="width: 83px;float: right;margin: 10px;" v-show="form.approvalStatus==3" @click="bohuifaqi()">驳回发起</el-button> -->
            
        </el-form>
    </el-tab-pane>
    <el-tab-pane label="自定义">   <el-form  class="demo-ruleForm" :model="form" ref="formRef" label-width="auto" style="max-width:400px;margin-left: 180px;margin-top: 30px;">
    <el-form-item label="是否三方合同:" prop="contract" :rules="[ { required: true, message: '必填' },]">
      <el-select v-model="form.contract"  >
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
            </el-select>
    </el-form-item>
    <el-form-item label="付款条件:" prop="condition">
      <el-select v-model="form.condition" >
                <el-option label="2/10" value="2/10" />
                <el-option label="5/10" value="5/10" />
            </el-select>
    </el-form-item>
    <el-form-item label="销售人员:" prop="salesperson">
      <el-input v-model="form.salesperson" />
    </el-form-item>
    <el-form-item label="最晚付款日期:" prop="latestDate">
      <el-date-picker
        v-model="form.latestDate"
        type="date"
        placeholder="最晚付款日期"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
      />
    </el-form-item>
    <el-form-item label=" test1:" prop="tests" :rules="[ { required: true, message: '必填' },]">
      <el-input v-model="form.tests" />
    </el-form-item>
  </el-form>
</el-tab-pane>
  </el-tabs>
  
  <h2 style="font-size: 17px;font-weight: 500; color: #409EFF; margin-top: 60px; margin-left: 50px; margin-bottom: 10px;" >采购/委外订单行信息</h2>
        <hr style='background-color:#d3d3d3; height:1px; border:none;'>

    <el-tabs type="border-card" style="margin-top: 30px;margin-left: 30px">
      <!-- 订单行的信息 -->
      <el-tab-pane label="订单行">
        <div class="demo-collapse">
          <el-collapse accordion> </el-collapse>
        </div>
        <div style="background-color: white; width: 100%; height: 100%">
          <el-button
            type="primary"
            style="float: right; margin-top: -10px; margin-right: 20px"
            @click="dialogFormVisible1=true"
            >+新增订单行</el-button
          >
          <div style="margin: 20px">
            <el-table :data="orderLinesList" style="width: 100%">
              <el-table-column prop="orderLineId" label="行号" />
              <el-table-column prop="inventoryInfoId" label="物料编码" />
              <el-table-column prop="itemName" label=" 物料名称" />
              <el-table-column prop="orderLinePrice" label="单价（不含税）" width="180" />
              <el-table-column prop="orderLineNum" label="数量	" />
              <el-table-column prop="unit" label="单位" />
              <el-table-column prop="bankAmount" label=" 金额（不含税）" width="180"/>
              <el-table-column prop="lineSummary" label="	摘要" />
              <el-table-column prop="handleTime" label="创建时间" width="180">
                <template #default="{ row }">
                  {{ moment(row.handleTime).format("YYYY-MM-DD HH:mm:ss") }}
                </template>
              </el-table-column>
              <el-table-column prop="handle" label="创建人" width="180" />
              <el-table-column label="操作" width="180">
          <template #default="{row}">
            <el-button
              size="small"
              @click="FanorderLines(row.orderLineId)"
              >编辑</el-button
            >
            <el-button size="small" @click="orderLinesDel(row.orderLineId)"
              >删除</el-button
            >
          </template>
        </el-table-column>
            </el-table>
          </div>
        </div>
          <!-- 新增 -->
          <el-dialog v-model="dialogFormVisible1" title="订单行新增" width="500">
          <el-form
            ref="ruleFormRef"
            style="max-width: 600px"
            :model="ruleForm"
            :rules="rules"
            label-width="auto"
            class="demo-ruleForm"
            :size="formSize"
            status-icon
          >
            <el-form-item label="物料" prop="inventoryInfoId">
              <el-select v-model="ruleForm.inventoryInfoId" placeholder="请选择物料">
          <el-option
            v-for="item in ItemInfoList"
            :label="item.itemName"
            :value="item.inventoryInfoId"
          />
        </el-select>
            </el-form-item>
            <el-form-item label="单价(不含税)" prop="orderLinePrice">
              <el-input v-model="ruleForm.orderLinePrice" />
            </el-form-item>
            <el-form-item label="数量" prop="orderLineNum">
              <el-input v-model="ruleForm.orderLineNum" />
            </el-form-item>
            <el-form-item label="单位" prop="unit">
              <el-select v-model="ruleForm.unit" >
                <el-option label="个/台" value="个/台" />
                <el-option label="次" value="次" />
                <el-option label="克" value="克" />
                <el-option label="小时" value="小时" />
                <el-option label="千克" value="千克" />
                <el-option label="毫升" value="毫升" />
                <el-option label="人" value="人" />
            </el-select>
            </el-form-item>
            <el-form-item label="行金额(不含税)" prop="bankAmount">
              <el-input v-model="totalSum" disabled />
            </el-form-item>
            <el-form-item label="行摘要" prop="lineSummary">
              <el-input v-model="ruleForm.lineSummary" />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取消</el-button>
              <el-button type="primary" @click="AddorderLines"> 确定 </el-button>
            </div>
          </template>
        </el-dialog>
        <!-- 修改 -->
        <el-dialog v-model="dialogFormVisible" title="订单行编辑" width="500">
          <el-form
            ref="ruleFormRef"
            style="max-width: 600px"
            :model="ruleForm"
            :rules="rules"
            label-width="auto"
            class="demo-ruleForm"
            :size="formSize"
            status-icon
          >
            <el-form-item label="物料" prop="inventoryInfoId">
              <el-select v-model="ruleForm.inventoryInfoId" placeholder="请选择物料">
          <el-option
            v-for="item in ItemInfoList"
            :label="item.itemName"
            :value="item.inventoryInfoId"
          />
        </el-select>
            </el-form-item>
            <el-form-item label="单价(不含税)" prop="orderLinePrice">
              <el-input v-model="ruleForm.orderLinePrice" />
            </el-form-item>
            <el-form-item label="数量" prop="orderLineNum">
              <el-input v-model="ruleForm.orderLineNum" />
            </el-form-item>
            <el-form-item label="单位" prop="unit">
              <el-select v-model="ruleForm.unit" >
                <el-option label="个/台" value="个/台" />
                <el-option label="次" value="次" />
                <el-option label="克" value="克" />
                <el-option label="小时" value="小时" />
                <el-option label="千克" value="千克" />
                <el-option label="毫升" value="毫升" />
                <el-option label="人" value="人" />
            </el-select>
            </el-form-item>
            <el-form-item label="行金额(不含税)" prop="bankAmount">
              <el-input v-model="totalSum" disabled />
            </el-form-item>
            <el-form-item label="行摘要" prop="lineSummary">
              <el-input v-model="ruleForm.lineSummary" />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取消</el-button>
              <el-button type="primary" @click="UpdateorderLines"> 确定 </el-button>
            </div>
          </template>
        </el-dialog>
      </el-tab-pane>
      <!-- 付款计划行 -->
      <el-tab-pane label="付款计划行">
        <div style="background-color: white;width: 100%;height: 100%;">
          <el-button type="primary" style="float: right;margin-top: -10px;margin-right: 20px;" @click="dialogFormVisible3=true">+新增付款计划</el-button>
   <div style="margin: 20px;">
     <el-table :data="PaymentPlansAddList" style="width: 100%">
<el-table-column prop="paymentPlanId" label="行号" />
<el-table-column prop="paymentPlanDate" label="付款计划时间" width="180">
  <template #default="{row}">
   {{ moment(row.paymentPlanDate).format("YYYY-MM-DD") }}
 </template>
</el-table-column>
<el-table-column prop="proportionPayment" label=" 付款比例（%）" width="80"/>
<el-table-column prop="paymentPrice" label="付款金额（不含税）" width="80"/>
<el-table-column prop="paymentAdvance" label="预付款"/>
<el-table-column prop="0" label=" 开票金额（含税）" width="180"/>
<el-table-column prop="0" label="已付款金额（含税）" width="180"/>
<el-table-column prop="remarks" label="备注"/>
<el-table-column prop="handleTime" label="创建时间" width="180">
 <template #default="{row}">
   {{ moment(row.handleTime).format("YYYY-MM-DD HH:mm:ss") }}
 </template>
</el-table-column>
<el-table-column prop="handle" label="创建人" width="80" />
<el-table-column label="操作" width="180">
          <template #default="{row}">
            <el-button
              size="small"
              @click="FanPaymentPlans(row.paymentPlanId)"
              >编辑</el-button
            >
            <el-button size="small" @click="PaymentPlansDel(row.paymentPlanId)"
              >删除</el-button
            >
          </template>
        </el-table-column>
</el-table>

   </div>
 
 </div>
 <!--新增付款计划-->
 <el-dialog v-model="dialogFormVisible3" title="付款计划新增" width="500">
    <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
    class="demo-ruleForm"
    :size="formSize"
    status-icon
  >
    <el-form-item label="付款计划时间" prop="paymentPlanDate">
      <el-date-picker
        v-model="ruleForm.paymentPlanDate"
        type="date"
        placeholder="付款计划时间"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
      />
    </el-form-item>
    <el-form-item label="付款比例" prop="proportionPayment">
      <el-input v-model="ruleForm.proportionPayment" />
    </el-form-item>
    <el-form-item label="付款金额(不含税)" prop="paymentPrice">
      <el-input v-model="ruleForm.paymentPrice" />
    </el-form-item>
    <el-form-item label="预付款" prop="paymentAdvance">
      <el-select v-model="ruleForm.paymentAdvance" >
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
            </el-select>
    </el-form-item>
    <el-form-item label="备注" prop="remarks">
      <el-input v-model="ruleForm.remarks" />
    </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">返回</el-button>
        <el-button type="primary" @click="PaymentPlansAdd">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
  
 <!--修改-->
 <el-dialog v-model="dialogFormVisible2" title="付款计划编辑" width="500">
    <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
    class="demo-ruleForm"
    :size="formSize"
    status-icon
  >
    <el-form-item label="付款计划时间" prop="paymentPlanDate">
      <el-date-picker
        v-model="ruleForm.paymentPlanDate"
        type="date"
        placeholder="付款计划时间"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
      />
    </el-form-item>
    <el-form-item label="付款比例" prop="proportionPayment">
      <el-input v-model="ruleForm.proportionPayment" />
    </el-form-item>
    <el-form-item label="付款金额(不含税)" prop="paymentPrice">
      <el-input v-model="ruleForm.paymentPrice" />
    </el-form-item>
    <el-form-item label="预付款" prop="paymentAdvance">
      <el-select v-model="ruleForm.paymentAdvance" >
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
            </el-select>
    </el-form-item>
    <el-form-item label="备注" prop="remarks">
      <el-input v-model="ruleForm.remarks" />
    </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">返回</el-button>
        <el-button type="primary" @click="UpdatePaymentPlans">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
  
      </el-tab-pane>
    </el-tabs>
    
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, readonly,computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import axios from "axios";
const formRef = ref<FormInstance>();
const apiurl = import.meta.env.VITE_APP_API_URL_ProductionAdd;
const apiurl1 = import.meta.env.VITE_APP_API_URL_ProductionShow;
const router = useRouter();
const route = useRoute();
import type { ComponentSize, FormInstance, FormRules } from "element-plus";
const dialogFormVisible = ref(false);
const dialogFormVisible2 = ref(false);
const dialogFormVisible1 = ref(false);
const dialogFormVisible3 = ref(false);
import moment from "moment";
import { ru } from "element-plus/es/locales.mjs";
//获取登录信息
const UserList = ref([]);
const LoadUserJSONData = () => {
  //读出数据
  const value = localStorage.getItem("userInfo");
  //反序列化JSON字符串
  UserList.value = JSON.parse(value);
  UserList.value.forEach((item: any) => {
    form.handle = item.userName;
    name.value = item.userName;
  });
};

let totalSum= ref(0);
// 计算行金额的计算属性
const aa= computed(() => {


  return Number(ruleForm.orderLinePrice) * Number(ruleForm.orderLineNum);
 
});
totalSum=aa;
console.log(totalSum);

//物料下拉
const ItemInfoList: any = ref([]);
const getItemInfoList = () => {
  axios
    .post(apiurl1 + "/api/ShowProducManagement/ShowItemInfo", {})
    .then((res) => {
      console.log(res);
      ItemInfoList.value = res.data.data;
    })
    .catch((err) => {
      console.log(err);
    });
};

//订单类型
const options=ref([])
const OrderType=()=>{
    axios.post(apiurl1+'/api/ShowProducManagement/PurchasingTypeShow',{}).then((res)=>{
        options.value=res.data.data
    })
}

//供应商
const options1=ref([])
const SuppliersList=()=>{
    axios.post(apiurl1+'/api/ShowProducManagement/SupplierShow',{}).then((res)=>{
        options1.value=res.data.data
    })
}

//项目
const options2=ref([])
const Projects=()=>{
    axios.post(apiurl1+'/api/ShowProduction/GetProjectShow',{}).then((res)=>{
        options2.value=res.data.data
    })
}

//部门
const options3=ref([])
const Departments=()=>{
    axios.get(apiurl1+'/api/ShowProduction/GetDepartment').then((res)=>{
        options3.value=res.data.data
    })
}

//供应商信息字段
const form = reactive({
  purchasinId: 0,
  purchasingNo: "",
  purchasingName: "",
  purchasingTypeId: "",
  projectId: "",
  purchasingDesc: "",
  suppliersId: "",
  orderAmount: 0,
  currency: "",
  advancePayment: "",
  startTime: "",
  endTime: "",
  signUpTime: "",
  purchasingStatus: "",
  taxType: "",
  taxRate: "",
  billing: 0,
  paidFor: 0,
  billMaking: "",
  departmentId: "",
  approvalStatus: 0,
  contract: "",
  condition: "",
  salesperson: "",
  latestDate:'',
  tests: "",
  handle: "张三",
  handleContext: "添加",
  pid: 0,
  isDelete: 0,
});

//采购/委外订单头信息修改
const UpdatePurchasings = () => {
  const data={

    purchasinId:route.query.purchasinId,
    purchasingNo: form.purchasingNo,
    purchasingName: form.purchasingName,
    purchasingTypeId: form.purchasingTypeId,
    projectId: form.projectId,
    purchasingDesc: form.purchasingDesc,
    suppliersId: form.suppliersId,
    orderAmount: form.orderAmount,
    currency: form.currency,
    advancePayment: form.advancePayment,
    startTime: form.startTime,
    endTime: form.endTime,
    signUpTime: form.signUpTime,
    purchasingStatus: form.purchasingStatus,
    taxType: form.taxType,
    taxRate: form.taxRate,
    billing: form.billing,
    paidFor: form.paidFor,
    billMaking: form.billMaking,
    departmentId: form.departmentId,
    approvalStatus: form.approvalStatus,
    contract: form.contract,
    // condition: form.condition,
    salesperson: form.salesperson,
    latestDate: form.latestDate,
    tests: form.tests,
  }
  console.log(data);  
  axios
    .post(apiurl + "/api/ProducManagement/PurchasingsUpdate",data)
    .then((res) => {
      console.log(res.data);
      ElMessage.success("修改成功");

    });
};


//字段
interface RuleForm {
  purchasinId: number
  //订单行信息字段
  orderLineId: number;
  inventoryInfoId: string;
  orderLinePrice: string;
  position: string;
  orderLineNum: string;
  unit: string,
  bankAmount: number
  branchNo: string
  lineSummary: string

    //付款计划信息字段
    paymentPlanId: number;
    paymentPlanDate: string;
    proportionPayment: string;
    paymentPrice: string;
    paymentAdvance: string;
    remarks: string,
  
}

const formSize = ref<ComponentSize>("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  purchasinId: 0,
  //订单行信息字段
  orderLineId: 0,
  inventoryInfoId: '',
  orderLinePrice: '',
  position: '',
  orderLineNum:'',
  unit: '',
  bankAmount: 0,
  branchNo: '',
  lineSummary: '',

    //付款计划信息字段
    paymentPlanId:0,
    paymentPlanDate: '',
    proportionPayment: '',
    paymentPrice:'',
    paymentAdvance:'',
    remarks: ''
});

//表单验证
const rules = reactive<FormRules<RuleForm>>({
  inventoryInfoId: [
    { required: true, message: "请选择", trigger: "blur" },
  ],
  orderLinePrice: [
    { required: true, message: "必填", trigger: "blur" },
  ],
  paymentPlanDate: [{ required: true, message: "必填", trigger: "blur" }],
  paymentPrice: [
    { required: true, message: '必填', trigger: 'blur' },
  ],
  proportionPayment: [
    { required: true, message: '必填', trigger: 'blur' },
  ],
  paymentAdvance: [
    { required: true, message: '必填', trigger: 'blur' },
  ]
});
//订单行添加
const AddorderLines=()=>{
  ruleForm.bankAmount=Number(ruleForm.orderLinePrice) * Number(ruleForm.orderLineNum)
    const data={
      inventoryInfoId: ruleForm.inventoryInfoId,
      orderLinePrice: ruleForm.orderLinePrice,
      orderLineNum: ruleForm.orderLineNum,
      unit: ruleForm.unit,
      bankAmount:ruleForm.bankAmount,
      lineSummary:ruleForm.lineSummary,
      purchasinId: route.query.purchasinId,
      handle: form.handle,
      handleContext: form.handleContext,
      pid: form.pid,
      isDelete: 0
    };
    alert(ruleForm.bankAmount)
    axios
    .post(apiurl + "/api/ProducManagement/OrderLinesAdd",data)
    .then((res) => {
      console.log(res);
      ElMessage.success("添加成功");
      dialogFormVisible1.value = false;
      Getorder()
    });

}
//定义一个数组来暂时存储订单行的信息
const orderLinesList:any = ref([]);
//订单行显示
const Getorder=()=>{
  axios.post(apiurl1+"/api/ShowProducManagement/OrderLinesShow",{
    purchasinId:route.query.purchasinId
  })
  .then((res)=>{
    console.log(res)
    orderLinesList.value=res.data.data
    //ruleForm.bankAmount
    res.data.data.forEach((item:any)=>{
      ruleForm.bankAmount+=item.orderLinePrice*item.orderLineNum
    })
  })
}

//反填订单行信息
const FanorderLines=(orderLineId:any)=>{
  dialogFormVisible.value=true;
axios.post(apiurl1+"/api/ShowProducManagement/OrderLinesSelId",{
  orderLineId:orderLineId
})
.then((res)=>{
  console.log(res)
  ruleForm.orderLineId=res.data.data[0].orderLineId;
  ruleForm.inventoryInfoId=res.data.data[0].inventoryInfoId;
  ruleForm.orderLinePrice=res.data.data[0].orderLinePrice;
  ruleForm.orderLineNum=res.data.data[0].orderLineNum;
  ruleForm.unit=res.data.data[0].unit;
  // ruleForm.bankAmount=res.data.data[0].bankAmount;
  ruleForm.bankAmount=totalSum;
  ruleForm.lineSummary=res.data.data[0].lineSummary;
  ruleForm.purchasinId=res.data.data[0].purchasinId;

})
}
//修改订单行信息
const UpdateorderLines=()=>{
  const data = {
    orderLineId: ruleForm.orderLineId,
    inventoryInfoId: ruleForm.inventoryInfoId,
    orderLinePrice: ruleForm.orderLinePrice,
    orderLineNum: ruleForm.orderLineNum,
    unit: ruleForm.unit,
    bankAmount: ruleForm.bankAmount,
    lineSummary: ruleForm.lineSummary,
  }
  alert(data.bankAmount)
  console.log(totalSum,1000);
  axios.put(apiurl + "/api/ProducManagement/OrderLinesUpdate",data).then((res) => {
    console.log(res.data);
    dialogFormVisible.value = false;
    // form.orderAmount=0;
    Getorder()
  });
}
//订单行信息删除
const orderLinesDel = (orderLineId: any) => {
  ElMessageBox.confirm("确定要删除么?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      axios
        .post(apiurl + "/api/ProducManagement/OrderLinesDelete", {
          orderLineId: orderLineId,
        })
        .then((res) => {
          console.log(res);
          ElMessage.success("删除成功");
          GetOrder();
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "删除失败",
      });
    });
};

//定义一个数组来暂时存储付款计划的信息
const PaymentPlansAddList:any = ref([]);
//添加付款计划
const PaymentPlansAdd=()=>{
    const data={
      paymentPlanDate: ruleForm.paymentPlanDate,
      proportionPayment: ruleForm.proportionPayment,
      paymentPrice: ruleForm.paymentPrice,
      paymentAdvance: ruleForm.paymentAdvance,
      remarks:ruleForm.remarks,
      purchasinId:route.query.purchasinId,
      handle: form.handle,
      handleContext: form.handleContext,
      pid: form.pid,
      isDelete: 0
    };
    axios
    .post(apiurl + "/api/ProducManagement/PaymentPlansCreateCommand",data)
    .then((res) => {
      console.log(res);
      ElMessage.success("添加成功");
      dialogFormVisible3.value=false
      GetPay()
    });
}

//付款计划显示
const GetPay=()=>{
  axios.post(apiurl1+"/api/ShowProducManagement/PaymentPlansShow",{
    purchasinId:route.query.purchasinId
  })
  .then((res)=>{
    console.log(res)
    PaymentPlansAddList.value=res.data.data
  })
}


//反填付款计划行信息
const FanPaymentPlans=(paymentPlanId:any)=>{
  dialogFormVisible2.value=true;
axios.post(apiurl1+"/api/ShowProducManagement/PaymentPlansSelId",{
  paymentPlanId:paymentPlanId
})
.then((res)=>{
  console.log(res)
  ruleForm.paymentPlanId=res.data.data[0].paymentPlanId;
  ruleForm.paymentPlanDate=res.data.data[0].paymentPlanDate;
  ruleForm.proportionPayment=res.data.data[0].proportionPayment;
  ruleForm.paymentPrice=res.data.data[0].paymentPrice;
  ruleForm.paymentAdvance=res.data.data[0].paymentAdvance;
  ruleForm.remarks=res.data.data[0].remarks;
})
}
//修改付款计划行信息
const UpdatePaymentPlans=()=>{
  const data = {
    paymentPlanId: ruleForm.paymentPlanId,
    paymentPlanDate: ruleForm.paymentPlanDate,
    proportionPayment: ruleForm.proportionPayment,
    paymentPrice: ruleForm.paymentPrice,
    paymentAdvance: ruleForm.paymentAdvance,
    remarks: ruleForm.remarks,
  }
  console.log(data,1000);
  axios.put(apiurl + "/api/ProducManagement/PaymentPlansUpdate",data).then((res) => {
    console.log(res.data);
    dialogFormVisible2.value = false;
    GetPay();
  });
}
//付款计划行信息删除
const PaymentPlansDel = (paymentPlanId: any) => {
  ElMessageBox.confirm("确定要删除么?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      axios
        .post(apiurl + "/api/ProducManagement/PaymentPlansDelete", {
          paymentPlanId: paymentPlanId,
        })
        .then((res) => {
          console.log(res);
          ElMessage.success("删除成功");
          GetPaymentPlans();
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "删除失败",
      });
    });
};

//采购/委外订单反填
const Fan=()=>{
axios.post(apiurl+"/api/ProducManagement/PurchasingsSelId",{
  purchasinId:route.query.purchasinId,
  purchasingNo:route.query.purchasingNo,
}).then(res=>{
  console.log(res.data.data,"反填");
  // orderLinesList.value=res.data.data.orderLinesList
  // PaymentPlansAddList.value=res.data.data.paymentPlansList
  form.purchasingNo=res.data.data[0].purchasingNo;
  form.purchasingName=res.data.data[0].purchasingName
  form.purchasingTypeId=res.data.data[0].purchasingTypeId
  form.projectId=res.data.data[0].projectId
  form.purchasingDesc=res.data.data[0].purchasingDesc
  form.suppliersId=res.data.data[0].suppliersId
  form.currency=res.data.data[0].currency
  form.advancePayment=res.data.data[0].advancePayment
  form.startTime=res.data.data[0].startTime
  form.endTime=res.data.data[0].endTime
  form.signUpTime=res.data.data[0].signUpTime
  form.purchasingStatus=res.data.data[0].purchasingStatus
  form.taxType=res.data.data[0].taxType
  form.taxRate=res.data.data[0].taxRate
  form.billing=res.data.data[0].billing
  form.paidFor=res.data.data[0].paidFor
  form.billMaking=res.data.data[0].billMaking
  form.departmentId=res.data.data[0].departmentId
  form.approvalStatus=res.data.data[0].approvalStatus
  form.contract=res.data.data[0].contract
  form.condition=res.data.data[0].condition
  form.salesperson=res.data.data[0].salesperson
  form.latestDate=res.data.data[0].latestDate
  form.tests=res.data.data[0].tests
})
}


// 审批
// const Submit=()=>{
//     axios.post(apiurl+'/api/ProducManagement/GetApprovalStatus',{
//       purchasinId :route.query.purchasinId,
//         approvalStatus:form.approvalStatus
//     }).then((res)=>{
//         if(res.data.code==1){
//             ElMessage({
//                 message: '审核通过',
//                 type: 'success',
//             })
//             ORderShow()
//         }else{
//             ElMessage.error(res.data.msg)
//         }
//     })
// }


const userId = ref(0);
const name = ref("");
const OrderSubmit=reactive({
  workflowDefinitionId: "Purchase01",
  title: "采购订单",
  formContent: route.query,
  version: 1,
  userId: userId.value,
  userName: name.value,
  workflowId: ""
})
const aaa = import.meta.env.VITE_APP_API_URL_StartWorkflowData;
//提交
const Submit1=()=>{
  if (name.value == "MaxAdmin") {
     userId.value = 1;
     name.value = "MaxAdmin";
   } else if (name.value == "Admin") {
    userId.value = 2;
     name.value = "admin";
   } else if (name.value == "李四") {
     userId.value = 4;
     name.value = "李四";
   } else {
     userId.value = 0;
     name.value = "";
   }
   const dataa = {
    purchasingNo: form.purchasingNo,
    Title: "采购委外",
   };
  axios
      .post(apiurl1 + "/api/ShowProducManagement/WorkflowInstanceQuery", dataa)
     .then((res: any) => {
       if (res.data.code > 0) {
         console.log(res.data);
         localStorage.setItem(
           "workflowIdaa",
           res.data.data[0].workflowInstanceId
           
         );
       }
     });
   console.log(localStorage.getItem("workflowIdaa"));
    axios.post(aaa+'/api/Workflow/StartWorkflowData',{
      workflowDefinitionId: "Purchase01",
      title: "采购委外",
      formContent: form.purchasingNo,
      version: 1,
      userId: userId.value,
      userName: name.value,
      workflowId:OrderSubmit.workflowId
    }).then((res)=>{
      if (res.data.code > 0) {
      ElMessage.success(res.data.msg);
      //删除数据
      localStorage.removeItem("workflowIdaa");
    } else {
      ElMessage.error(res.data.msg);
    }
    })



    axios.post(apiurl+'/api/ProducManagement/ApprovalStatusSubmit',{
      purchasinId :route.query.purchasinId,
        approvalStatus:form.approvalStatus,
        name: name.value,
    }).then((res)=>{
      console.log(res,11111)
      ElMessage.success(res.data.msg)
      ORderShow()
    })
}




//提交
// const Submit1=()=>{
//     axios.post(apiurl+'/api/ProducManagement/ApprovalStatusSubmit',{
//       purchasinId :route.query.purchasinId,
//         approvalStatus:form.approvalStatus,
//         name: name.value,
//     }).then((res)=>{
//       console.log(res,11111)
//       ElMessage.success(res.data.msg)
//       ORderShow()
//     })
// }

//驳回
// const Overrule=()=>{
//     axios.post(apiurl+'/api/ProducManagement/ApprovalStatusOverrule',{
//       purchasinId :route.query.purchasinId,
//       approvalStatus:form.approvalStatus
//     }).then((res)=>{
//         if(res.data.code==1){
//             ElMessage({
//                 message: '已驳回',
//                 type: 'success',
//             })
//             ORderShow()
//         }else{
//             ElMessage.error(res.data.msg)
//         }
//     })
// }


//审批
const Submit = () => {
  if (name.value == "MaxAdmin") {
    userId.value = 1;
    name.value = "MaxAdmin";
  } else if (name.value == "Admin") {
    userId.value = 2;
    name.value = "admin";
  } else if (name.value == "李四") {
    userId.value = 4;
    name.value = "李四";
  } else {
    userId.value = 0;
    name.value = "";
  }
  //查询编号信息
  const dataa = {
    purchasingNo: form.purchasingNo,
    title: "采购委外",
  };
  axios
    .post(apiurl1 + "/api/ShowProducManagement/WorkflowInstanceQuery", dataa)
    .then((res: any) => {
      if (res.data.code > 0) {
        //存入数据
        localStorage.setItem(
          "workflowIdaa",
          res.data.data[0].workflowInstanceId
        );
        alert(res.data.data[0].workflowInstanceId)
      }
    });
   
  console.log(localStorage.getItem("workflowIdaa"));
  //开始审批
  const data = {
    workflowId: localStorage.getItem("workflowIdaa"),
    auditOperateType: 3,
    userId: userId.value,
    userName: name.value,
    rejectToStepId: "",
    remark: "通过",
  };
  alert(data.workflowId);
  console.log(data, "开始审批");
  axios.post(aaa + "/api/Workflow/UpAuditData", data).then((res: any) => {
    console.log(res.data);
    if (res.data.code > 0) {
      ElMessage.success(res.data.msg);
       //删除数据
      localStorage.removeItem("workflowIdaa");
      ORderShow()
    } else {
      ElMessage.error(res.data.msg);
    }
  });

  //可不做  （状态修改）

  axios.post(apiurl+'/api/ProducManagement/GetApprovalStatus',{
      purchasinId :route.query.purchasinId,
      name: name.value,
        approvalStatus:form.approvalStatus
    }).then((res)=>{
        if(res.data.code==1){
            // ElMessage({
            //     message: '审核通过',
            //     type: 'success',
            // })
            
        }else{
            ElMessage.error(res.data.msg)
        }
    })
};
 //驳回
 const bohui = () => {
  if (name.value == "MaxAdmin") {
     userId.value = 1;
     name.value = "MaxAdmin";
   } else if (name.value == "Admin") {
    userId.value = 2;
     name.value = "admin";
   } else if (name.value == "李四") {
     userId.value = 4;
     name.value = "李四";
   } else {
     userId.value = 0;
     name.value = "";
   }
   const dataa = {
    purchasingNo: form.purchasingNo,
    title: "采购委外",
   };
  axios
      .post(apiurl1 + "/api/ShowProducManagement/WorkflowInstanceQuery", dataa)
     .then((res: any) => {
       if (res.data.code > 0) {
         console.log(res.data);
         localStorage.setItem(
           "workflowIdaa",
           res.data.data[0].workflowInstanceId
           
         );
       }
     });
   console.log(localStorage.getItem("workflowIdaa"));
   //在数据从本地取出后  格式为  "123" 的格式 在添加到下面data时 需要去掉  ""
   //workflowId.value = workflowId.value.substring(1, workflowId.value.length - 1);
   const data = {
     workflowId: localStorage.getItem("workflowIdaa"),
     auditOperateType: 2,
     userId: userId.value,
     rejectToStepId: "",
     remark: "驳回",
   };
   console.log(data, "开始驳回");
   axios.post(aaa + "/api/Workflow/UpAuditData", data).then((res: any) => {
     console.log(res.data);
     if (res.data.code > 0) {
       ElMessage.success(res.data.msg);
       //删除数据
       localStorage.removeItem("workflowIdaa");
     } else {
       ElMessage.error(res.data.msg);
     }
   });

   axios.post(apiurl+'/api/ProducManagement/ApprovalStatusOverrule',{
      purchasinId :route.query.purchasinId,
      approvalStatus:form.approvalStatus,
      name: name.value,
    }).then((res)=>{
        if(res.data.code==1){
            ElMessage({
                message: '已驳回',
                type: 'success',
            })
            ORderShow()
        }else{
            ElMessage.error(res.data.msg)
        }
    })

 };
//驳回发起
// const bohuifaqi = () => {
//   if (name.value == "MaxAdmin") {
//     userId.value = 1;
//     name.value = "MaxAdmin";
//   } else if (name.value == "Admin") {
//     userId.value = 2;
//     name.value = "admin";
//   } else if (name.value == "李四") {
//     userId.value = 4;
//     name.value = "李四";
//   } else {
//     userId.value = 0;
//     name.value = "";
//   }
//   const dataa = {
//     purchasingNo: form.purchasingNo,
//     title: "采购委外",
//   };
//   axios
//       .post(apiurl1 + "/api/ShowProducManagement/WorkflowInstanceQuery", dataa)
//      .then((res: any) => {
//        if (res.data.code > 0) {
//          console.log(res.data);
//          localStorage.setItem(
//            "workflowIdaa",
//            res.data.data[0].workflowInstanceId
           
//          );
//        }
//      });
//   const data = {
//     workflowId: localStorage.getItem("workflowIdaa"),
//     auditOperateType: 0,
//     userId: userId.value,
//     userName: name.value,
//     rejectToStepId: "",
//     remark: "驳回发起",
//   };
//   axios.post(aaa + "/api/Workflow/UpDateRerectData", data).then((res: any) => {
//     console.log(res.data);
//     if (res.data.code > 0) {
//       ElMessage.success(res.data.msg);
//       //删除数据
//       localStorage.removeItem("workflowIdaa");
//     } else {
//       ElMessage.error(res.data.msg);
//     }
//   });

//   axios.post(apiurl+'/api/ProducManagement/ApprovalStatusOverrule',{
//       purchasinId :route.query.purchasinId,
//       approvalStatus:form.approvalStatus,
//       name: name.value,
//     }).then((res)=>{
//         if(res.data.code==1){
//             ElMessage({
//                 message: '已驳回',
//                 type: 'success',
//             })
//             ORderShow()
//         }else{
//             ElMessage.error(res.data.msg)
//         }
//     })
 
// };


const ORderShow=()=>{
    router.push('/ProducManagement/PurchasingsQuery')
}

//钩子函数
onMounted(() => {
  Projects()
  Departments()
  OrderType()
  SuppliersList()
  getItemInfoList()
      Fan()
      GetPay()
      Getorder()
      LoadUserJSONData()
});

</script>
